package com.phone.rest.modular.bussiness.controller.front;

import com.phone.core.base.controller.BaseController;
import com.phone.core.util.CommonUtil;
import com.phone.core.util.DateUtil;
import com.phone.core.util.HttpUtil;
import com.phone.rest.common.persistence.model.Member;
import com.phone.rest.common.persistence.model.Msg;
import com.phone.rest.config.properties.WxProperties;
import com.phone.rest.modular.auth.util.JwtTokenUtil;
import com.phone.rest.modular.bussiness.service.IMemberSv;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by zengzr on 2017/10/18.
 */
@RestController
@RequestMapping("api")
public class WxInitController extends BaseController {

    @Autowired
    private WxProperties wxProperties;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    IMemberSv memberSv;

    /**
        * @Description: 测试
        * @author zengzr
        * @date 2017/10/20
        * @version V1.0
        */
    @RequestMapping("test")
    public Object test(@RequestBody Msg msg){

        return CommonUtil.responseSuccess(CommonUtil.MSG_SUCCESS,null);
    }
    /**
    * @Description: 微信登陆
    * @author zengzr
    * @date 2017/10/19
    * @version V1.0
    */
    @RequestMapping("wxInit")
    public void wxInit(@RequestParam String code){
        if (StringUtils.isNotEmpty(code)){
            //获取token
            StringBuffer sb=new StringBuffer(wxProperties.getToken_Url());
            sb.append("appid="+wxProperties.getAppid());
            sb.append("&secret="+wxProperties.getSecret());
            sb.append("&code="+code);
            sb.append("&grant_type=authorization_code");

            final String rs= HttpUtil.RequestGetUrl(sb.toString());
            logger.info("[*] rs:"+rs);
            JSONObject obj = JSONObject.fromObject(rs);
            String scope = "";
            String unionId = "";
            String accessToken = "";
            String openId="";

            if (obj.containsKey("scope")) {
                scope = obj.getString("scope");
            }
            if (obj.containsKey("openid")) {
                openId = obj.getString("openid");
            }
            if (obj.containsKey("unionid")) {
                unionId = obj.getString("unionid");
            }
            if (obj.containsKey("access_token")) {
                accessToken = obj.getString("access_token");
            }
            //获取用户基本信息
            if (accessToken != null) {
                sb.setLength(0);
                sb.append(wxProperties.getUserinfo_Url());
                sb.append("access_token=").append(accessToken);
                sb.append("&openid=").append(openId);
                sb.append("&lang=zh_CN");
                String ret = HttpUtil.RequestGetUrl(sb.toString());
                logger.info("userInfo" + ret);
                JSONObject userobj = JSONObject.fromObject(ret);
                String nickname = userobj.getString("nickname");
                String headimgurl = userobj.getString("headimgurl");
                //0未知1男2女
                String sex = userobj.getString("sex");
                String province = userobj.getString("province");
                String city = userobj.getString("city");
                Member m=new Member();
                m.setOpenId(openId);
                m.setNickName(nickname);
                m.setHeadImg(headimgurl);
                m.setProvince(province);
                m.setCity(city);
                m.setSex(Integer.parseInt(sex));
                if(StringUtils.isNotEmpty(openId)){
                    this.login(m);
                }
            }


        }
    }
    /**
        * @Description: 微信登陆或者添加
        * @author zengzr
        * @date 2017/10/19
        * @version V1.0
        */
    public Object login(Member newm) {
        Map map=new HashMap();
        //是否存在该用户
        Member oldm=memberSv.selectById(newm.getOpenId());
        final String randomKey = jwtTokenUtil.getRandomKey();
        final String token = jwtTokenUtil.generateToken(newm.getOpenId(), randomKey);
        if (oldm==null){
            newm.setStatus(1);
            newm.setCreateTime(DateUtil.defaultdate());
            newm.setToken(token);
           try {
               memberSv.insert(newm);
           }catch (Exception e){
               e.printStackTrace();
               return CommonUtil.responseError("初始化用户失败",null);
           }
            map.put("member",newm);
        }else if(oldm.getStatus()==2){
            return CommonUtil.responseError("该用户已经被冻结",null);
        }else if (oldm.getStatus()==1){
            map.put("member",oldm);
            //同步微信信息
            oldm.setToken(token);
            try {
                memberSv.update(oldm);
            }catch (Exception e){
                e.printStackTrace();
                return CommonUtil.responseError("同步资料失败",null);
            }
        }
        map.put("token",token);
        map.put("randomKey",randomKey);
        return CommonUtil.responseSuccess("登陆成功",map);
    }

}